from django.shortcuts import render, redirect
from django.urls import reverse

from common.models import Shop,User

def index(request):
    '''前台页面'''
    return render(request, "web/index.html")

def login(request):
    '''登录页面'''
    # 查找所有的店铺信息
    shoplist = Shop.objects.all()
    context = {'shopl': shoplist}
    return render(request, "web/login.html",context)

def dologin(request):
    '''会员执行登录'''
    # 校验验证码
    verifycode = request.session['verifycode']
    code = request.POST['code']
    if verifycode != code:
        context = {'info':'验证码错误！'}
        return render(request,"web/login.html",context)

    try:
        #根据账号获取登录者信息
        user = User.objects.get(username=request.POST['username'])
        #判断当前用户是否是后台管理员用户
        if user.state == 0:
            # 验证密码
            import hashlib
            m = hashlib.md5()
            m.update(bytes(request.POST['password'],encoding="utf8"))
            if user.password == m.hexdigest():
                # 此处登录成功，将当前登录信息放入到session中，并跳转页面
                request.session['vipuser'] = user.toDict()
                return redirect(reverse('index'))
            else:
                context = {'info':'登录密码错误！'}
        else:
            context = {'info':'此用户为非法用户！'}
    except:
        context = {'info':'登录账号错误！'}
    return redirect(reverse('index_dologin'),context)